package com.yh.correct.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.parser.Token;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.SysPermission;
import com.yh.correct.model.SysUser;
import com.yh.correct.model.vo.Node;
import com.yh.correct.service.ISysUserService;
import com.yh.correct.shiro.TreeUtil;

/**
 * 登陆页控制类
 * 
 * @author Administrator
 *
 */
@Controller
public class LoginController {
	/**
	 * 日志
	 */
	private static Logger logger = LogManager.getLogger(LoginController.class);
	/**
	 * 系统用户服务层
	 */
	@Autowired
	private ISysUserService userService;
	/**
	 * 系统登录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toLogin", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, @RequestParam("password") String password,
			@RequestParam(value="rememberMe",required=false) Boolean rememberMe,Model model) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		if(rememberMe!=null){
			token.setRememberMe(rememberMe);
		}
		try {
			subject.login(token);
		} catch (UnknownAccountException uae) {
			logger.info("未知账户");
		} catch (IncorrectCredentialsException ice) {
			logger.info("密码不正确");
		} catch (LockedAccountException lae) {
			logger.info("账户已锁定");
		} catch (ExcessiveAttemptsException eae) {
			logger.info("用户名密码次数过多");
		} catch (AuthenticationException ae) {
			logger.info("用户名或密码不正确");
		} catch(Exception ex){
			logger.info("未知的异常");
		}
		if (subject.isAuthenticated()) {
			SysUser user=(SysUser) subject.getPrincipal();
			logger.debug(user);
			model.addAttribute("user", user);
			return "/index";
		} else {
			return "redirect:/login.html";
		}
	}

	/**
	 * 获取用户的菜单
	 * @param userid
	 * @return
	 */
	@RequestMapping("/getMenus")
	@ResponseBody
	public ResultData getUserMenus(Integer userid){
		List<SysPermission> menus=null;
		try {
			menus=userService.findMenuListById(userid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//菜单转换
		List<Node> data=new ArrayList<Node>();
		logger.debug(menus);
		for(SysPermission m:menus){
			Node node=new Node();
			node.setMenuid(m.getId());
			node.setMenuname(m.getName());
			node.setPid(m.getPid());
			node.setUrl(m.getUrl());
			node.setIcon(m.getIcon());
			data.add(node);
		}
		List<Node> tree=TreeUtil.getTree(data);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(tree);
		logger.debug(tree);
		return rd;

	}
	
	/**
	 * 没有权限跳转到拒绝访问页面
	 * @return
	 */
	@RequestMapping(value="/index")
	private String toIndex(){
		return "index";
	}
	
	/**
	 * 没有权限跳转到拒绝访问页面
	 * @return
	 */
	@RequestMapping(value="/refuse")
	private String toRefuse(){
		return "forward:/refuse.html";
	}
	
	/**
	 * 注销登陆
	 * 
	 * @return
	 */    
	@RequestMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:login";
	}
}
